import math
import time
import matplotlib.pyplot as plt
import cupy as cp

# 定义余弦脉冲函数
def cos_pulse(t, shift, width):
    return cp.cos(math.pi / width / 2 * (t - shift)) * ((-width <= t - shift) & (t - shift <= width))

# 使用梯形积分法计算积分
def trapezoidal_integration(func, a, b, num_points=1000):
    x = cp.linspace(a, b, num_points)
    y = func(x)
    dx = (b - a) / (num_points - 1)
    return cp.trapz(y, dx=dx)

# 计算两个余弦脉冲的重合面积
def overlap_area(pred_width, target_width, t1, t2):
    px1, px2 = t1 - pred_width, t1 + pred_width
    tx1, tx2 = t2 - target_width, t2 + target_width

    union_x1 = min(px1, tx1)
    union_x2 = max(px2, tx2)
    Left = min(- pred_width, - target_width)
    Right = max(+ pred_width, + target_width)

    integrand = lambda t: cos_pulse(t, t1, pred_width) * cos_pulse(t, t2, target_width)
    area_over = trapezoidal_integration(integrand, union_x1, union_x2)

    area_A = 4 / math.pi * pred_width
    area_B = 4 / math.pi * target_width
    return area_over, area_A, area_B

# 计算两个余弦脉冲的总覆盖面积
def calculate_iou(preds, target, pred_width, target_width):
    s_overlap, s_a, s_b = overlap_area(pred_width, target_width, preds, target)
    G = 0
    iou = s_overlap / (s_a + s_b - s_overlap + 1e-9)
    return iou, s_overlap

# 参数设置
width = 20
pred_width = width * 3.14
target_width = width / 2
target = 0  # 目标中心点位置固定为0
T1 = time.time()

# 遍历pred从-80到80
preds = cp.linspace(-80, 80, 161)  # 161个点，包括-80和80
ious, s_overlap = zip(*[calculate_iou(pred, target, pred_width=pred_width, target_width=target_width) for pred in preds])

# 计算1 - iou
one_minus_ious = cp.array([1 - iou for iou in ious])
T2 = time.time()
print('程序运行时间:%s毫秒' % ((T2 - T1) * 1000))

# 绘图
plt.figure(figsize=(10, 6))
plt.plot(cp.asnumpy(preds), cp.asnumpy(one_minus_ious), marker='o', label='1 - IoU')
plt.title('1 - IoU, Intersection, and Union vs Prediction Offset')
plt.xlabel('Prediction Offset')
plt.ylabel('Values')
plt.legend()
plt.grid(True)
plt.show()